<?php

namespace app\index\controller;

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose
 */
use GatewayWorker\Lib\Gateway;
use think\Db;
use think\facade\Log;

class Events
{


  /*  public static function onConnect($client_id)
    {

      Gateway::sendToClient($client_id, json_encode(array(
            'type'      => 'init',
            'client_id' => $client_id
        )));
    }*/




    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $message)
    {
        $message_data = json_decode($message, true);
        if (isset($message_data['type'])) {
            $user_id =0;
            if (isset( $message_data['user_id'])) {
                $user_id =  $message_data['user_id'];
            }
            switch ($message_data['type']){
                case 'init':
//                    $bindClient = Gateway::getClientIdByUid($user_id);
//                    $bindClient&&  Gateway::unbindUid($bindClient, $user_id);
                    Gateway::bindUid($client_id, $user_id);
                    $sendmsg = ['type'=> 'init','client_id' => $client_id];
                    $sendmsg = json_encode($sendmsg);
                    Gateway::sendToClient($client_id, $sendmsg);
                    db('log')->insertGetId([
                        'client_id' => $client_id,
                        'text' => $user_id,
                        'status' => 'init'
                    ]);
                    return null;
                    break;
                case 'ping':
                    return null;
                    break;
                default:
                    break;
            }

        }
        $onlineUidlist = self::getOnlineData();
        db('log')->insertGetId([
            'client_id' => $client_id,
            'text' => json_encode($onlineUidlist),
            'status' => 'online',
        ]);

            $new_message = array(
                'from_client_id'        => $message_data['from_client_id'],
                'from_client_name'      => $message_data['from_client_name'],
                'from_client_avatarurl' => $message_data['from_client_avatarurl'],
                'to_client_id'          => $message_data['to_client_id'],
                'to_client_name'        => $message_data['to_client_name'],
                'to_client_avatarurl'   => $message_data['to_client_avatarurl'],
                'content'               => nl2br(htmlspecialchars($message_data['content'])),
                'cdate'                 => date('Y-m-d H:i:s'),
                'ctime'                 => time()
            );
            // 非空验证
        if (!trim($message_data['content'])) {
            return null;
        }

            $res = db('chat')->insertGetId($new_message);
          if (!$res) {
               db('log')->insertGetId([
                        'client_id' => $client_id,
                        'text' => 'to_user_id:'.$message_data['to_client_id'].'插入记录失败,消息记录插入失败'.json_encode($new_message).json_encode($onlineList),
                        'status' => 'send fail'
                ]);
          }
          ///////////////new ////////////////
         $isOnline = Gateway::isUidOnline( $message_data['to_client_id']);
          if ($isOnline) {
              $sendmsg = json_encode($new_message);
              Gateway::sendToUid( $message_data['to_client_id'],$sendmsg);
          } else {
              db('log')->insertGetId([
                  'client_id' => $client_id,
                  'text' => $message_data['to_client_id'].'用户不在线',
                  'status' => 'send fail'
              ]);
          }
          return null; //end ;
          //////////////new end ...................
          /////old

           $user = db('user')->find($message_data['to_client_id']);
            $toClient = '';
            if ($user&&$user['client_id']) {
                $toClient = $user['client_id'];
            }else {
                  db('log')->insertGetId([
                        'client_id' => $client_id,
                        'text' => 'to_user_id:'.$$message_data['to_client_id'].'查询用户失败，无此用户:',
                        'status' => 'send fail'
                 ]);
                return false;
            }
            $isOnline = Gateway::isOnline($toClient);

            if ($toClient&& $isOnline) {
                $new_message['client_id'] = $client_id;

                 Gateway::sendToClient($toClient, json_encode($new_message));

                // db('log')->insertGetId([
                //         'client_id' => $client_id,
                //         'text' => 'toClient:'.$toClient.'in message:'. json_encode($new_message),
                //         'status' => 'success'
                //  ]);
                return;
            }else{
                 db('log')->insertGetId([
                        'client_id' => $client_id,
                        'text' => 'toClient:'.$toClient.'in isOnline:'. $isOnline,
                        'status' => 'send fail'
                 ]);
            }

    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        $user_id = Gateway::getUidByClientId($client_id);
        var_export([$client_id=>$user_id,'onClose']);
        $user = \app\index\model\User::where('id', $user_id)->find();
        if ($user) {
            db('log')->insertGetId([
                    'client_id' => $client_id,
                    'text' => '用户断开链接'.$user->id.'--'.$user->nickName,
                    'status' => 'close'
             ]);
        } else {
            $msg = 'websocket close but user is not found'.$client_id;
            db('log')->insertGetId([
                    'client_id' => $client_id,
                    'text' => $msg,
                    'status' => 'close fail'
             ]);
            // echo $msg;
            Log::error($msg);
        }

       // 广播 xxx logout
       //GateWay::sendToAll("client[$client_id] logout\n");
    }



    public function chattingRecords()
    {
        $data = Db::name('chatting_records')->limit(20)->order('create_time desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['avatar'] = getFileUrl($v['avatar']);
        }
        $this->result($data);
    }
    public static function onWebSocketConnect( $client_id, array $data){
        if (isset($data['get']['user_id'])) {
            $user_id = $data['get']['user_id'];
            Gateway::bindUid($client_id, $user_id);
        }
    }

/*    public static function onWebSocketConnect( $client_id, array $data){

        if (isset($data['get']['user_id'])) {

            $user_id = $data['get']['user_id'];
            $user = \app\index\model\User::find( $user_id);
            if ( !$user) {
                   Gateway::sendToClient($client_id, json_encode(['type'=>'notice','msg'=> '链接认证失败，请重试key无效']));
                db('log')->insertGetId([
                    'client_id' => $client_id,
                    'text' => '链接认证失败，请重试key无效'. $user_id,
                    'status' =>'init fail'
                ]);
                   Gateway::closeClient($client_id);
            }

            if (self::isOwnClient($client_id, $user)) {
                db('log')->insertGetId([
                    'client_id' => $client_id,
                    'text' => 'init--user_id'. $user_id,
                    'status' =>'init 2次'
                ]);
                return false;// 是自己
            };

            $user_id  = $user['id'];
            ////-----
            self::closeOldClient($client_id, $user);

            $res = db('user')->where('id', $user_id)->update(['client_id'=>$client_id]);
            Gateway::sendToClient($client_id, json_encode(array(
                'type'      => 'init',
                'client_id' => $client_id
            )));


               $onlineList = Gateway::getAllClientIdList();
               // var_dump($onlineList);

              db('log')->insertGetId([
                              'client_id' => $client_id,
                              'text' => 'init--'.'user--'.$user->id.'online_clients'.json_encode($onlineList),
                              'status' =>'init success'
                       ]);

            if (!$res) {
                  Gateway::sendToClient($client_id, json_encode(['type'=>'notice','msg'=> '链接认证失败，请重试']));
                  Gateway::closeClient($client_id);
            }


        }  else {
                  Gateway::sendToClient($client_id, json_encode(['type'=>'notice','msg'=> '链接认证失败，无认证参数']));
                  Gateway::closeClient($client_id);
        }

    }*/

    public static function closeOldClient($nowClient,$user)
    {
        if ($user['client_id'] && $user['client_id']!== $nowClient) {
           Gateway::closeClient($user['client_id']);
        }
    }

    public static function isOwnClient($nowClient,$user)
    {
        if ($user['client_id'] && $user['client_id'] == $nowClient) {
           return true;
        }
        return false;
    }

    public  static function getOnlineData()
    {
        $clientList = Gateway::getAllClientIdList();
        $uids = Gateway::getAllUidList();
        $arr = [];
        foreach ($clientList as $key=>$val) {
            $arr[$key] = Gateway::getUidByClientId($val);
        }
        return ['auto'=>$arr,'userids'=>$uids,'clientids'=>$clientList];
    }
}
